<template>
  <Dialog v-model="dialogVisible" title="分配用户" width="900">
    <el-form label-width="80px">
      <el-form-item label="用户分配">
        <el-transfer
          v-model="selectedUserIds"
          :data="transferData"
          :titles="['待分配用户', '已分配用户']"
          :button-texts="['移除', '分配']"
          filterable
          filter-placeholder="搜索用户"
          style="text-align: left; display: inline-block"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button :disabled="loading" type="primary" @click="submit">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import * as CatTaskApi from '@/api/pm/cattask'

defineOptions({ name: 'PmCatTaskAssignUsers' })

const message = useMessage()

const dialogVisible = ref(false)
const loading = ref(false)
const taskId = ref<number>()
const selectedUserIds = ref<number[]>([])
const transferData = ref<any[]>([])

// 获取用户分配状态
const getUserAssignStatus = async (jobId: number) => {
  try {
    const data = await CatTaskApi.getUserAssignStatus({ jobId })
    const { assignedUsers = [], unassignedUsers = [] } = data || {}
    
    // 构建穿梭框数据格式
    const allUsers = [...assignedUsers, ...unassignedUsers]
    transferData.value = allUsers.map(user => ({
      key: user.id,
      label: `${user.nickname} (${user.username})`,
      disabled: false
    }))
    
    // 已分配的用户ID
    selectedUserIds.value = assignedUsers.map(user => user.id)
  } catch (error) {
    console.error('获取用户分配状态失败:', error)
    message.error('获取用户分配状态失败')
  }
}

const open = async (id: number) => {
  dialogVisible.value = true
  taskId.value = id
  selectedUserIds.value = []
  transferData.value = []
  
  // 获取用户分配状态
  await getUserAssignStatus(id)
}

defineExpose({ open })

const emit = defineEmits(['success'])
const submit = async () => {
  if (!taskId.value) return
  loading.value = true
  try {
    await CatTaskApi.assignUsers({ jobId: taskId.value, userIds: selectedUserIds.value })
    message.success('分配成功')
    dialogVisible.value = false
    emit('success')
  } finally {
    loading.value = false
  }
}
</script>

<style scoped> 

:deep(.el-transfer-panel) {
  width: 250px;
}

:deep(.el-transfer-panel__body) {
  height: 400px;
}

:deep(.el-transfer-panel__list) {
  height: 400px;
}

</style>



